<template>
  <div class="table-box">
    <ProTable
      :columns="columns"
      :request-api="getRegion"
      :tree-props="{ children: 'districts', hasChildren: 'hasChildren' }"
      :init-param="initParams"
      ref="regionRef"
    >
      <template #tableHeader="scope">
        <el-button v-if="initParams.id !== ''" :icon="Back" @click="back()">返回</el-button>
        <el-button type="primary" @click="addRootRegion()" v-if="initParams.id === ''">新增行政区</el-button>
        <el-button type="danger" @click="deleteRegion(scope.selectedListIds)" :disabled="scope.selectedListIds.length === 0"
          >批量删除</el-button
        >
      </template>
      <template #level="{ row }">
        {{ operaProvince(row.level) }}
      </template>
      <template #opera="{ row }">
        <div class="flex flex-wrap justify-center">
          <el-button link v-if="row.level === 'city'" @click="setSite(row)">设置站长</el-button>
          <el-button link v-if="row.level === 'city' && row.real_name" @click="release(row)">解绑站点</el-button>
          <el-button link @click="enter(row)" v-if="row.level !== 'custom'">进入</el-button>
          <el-button link @click="addRegion(row)">新增</el-button>
          <el-button link @click="editRegion(row)">编辑</el-button>
          <el-button link @click="deleteRegion([row.id])">删除</el-button>
        </div>
      </template>
      <template #is_hot="{ row }">
        <div v-if="row.level !== 'city'">
          <el-tag type="danger">否</el-tag>
        </div>
        <div v-else>
          <el-switch
            :active-value="true"
            :inactive-value="false"
            active-text="热门"
            inactive-text="非热门"
            v-model="row.is_hot"
            @change="changeHot(row)"
          ></el-switch>
        </div>
      </template>
      <template #is_default="{ row }">
        <div v-if="row.level !== 'city'">
          <el-tag type="danger">否</el-tag>
        </div>
        <div v-else>
          <el-switch
            :active-value="true"
            :inactive-value="false"
            active-text="是"
            inactive-text="否"
            v-model="row.is_default"
            @change="changeDefault(row)"
          ></el-switch>
        </div>
      </template>
      <template #manager="{ row }">
        <div v-show="row.username">
          <div>
            管理者:<el-tag type="success">{{ row.real_name }}</el-tag>
          </div>
          <div class="my-5px">
            过期时间:<el-tag type="success">{{ dayjs(row.over_time).format("YYYY-MM-DD") }}</el-tag>
          </div>
        </div>
        <div v-show="!row.username">无</div>
      </template>
    </ProTable>
    <regionDrawer ref="regionDrawerRef"></regionDrawer>
    <siteManager ref="siteRef"></siteManager>
  </div>
</template>

<script setup lang="ts">
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { Back } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import {
  addRegion as addRegionApi,
  getRegion,
  editRegion as editRegionApi,
  deleteRegion as deleteApi,
  setHot,
  setDefault,
  releaseSite
} from "@/api/modules/region";
import { reactive, ref } from "vue";
import regionDrawer from "./components/regionDrawer.vue";
import { useHandleData } from "@/hooks/useHandleData";
import siteManager from "./components/siteManager.vue";

// 解绑站点
const release = async (row: any) => {
  try {
    await useHandleData(releaseSite, { region: row.id, id: row.user_id }, "解绑该站点");
    regionRef.value?.getTableList();
  } catch (error) {}
};

// 设置站长
const siteRef = ref<InstanceType<typeof siteManager> | null>();

const setSite = (row: any) => {
  const params: any = {
    row: { real_name: row.real_name, user_id: row.user_id, over_time: row.over_time, id: row.id },
    getTable: regionRef.value?.getTableList
  };
  siteRef.value?.open(params);
};

const changeHot = async (row: any) => {
  await setHot({ city: row.id, isHot: row.isHot });
};

const changeDefault = async (row: any) => {
  await setDefault({ city: row.id, isDefault: row.isDefault });
  regionRef.value?.getTableList();
};

const columns: ColumnProps[] = [
  { type: "selection", width: 50 },
  { prop: "sort", label: "排序值", width: 80 },
  { prop: "name", label: "区域名称", search: { el: "input" }, width: 200 },
  { prop: "prefix", label: "网址前缀", width: 100 },
  { prop: "alias", label: "别名", width: 150 },
  { prop: "is_hot", label: "是否为热门", width: 180 },
  { prop: "manager", label: "管理者", width: 200 },
  { prop: "is_default", label: "是否为默认城市", width: 150 },
  { prop: "opera", label: "操作" }
];

const initParams = reactive({ id: "", pageSize: 10, pageNum: 1 });
const backInitParams = reactive<any[]>([]);

// ---------按钮操作
const regionRef = ref<InstanceType<typeof ProTable> | null>();

const enter = (row: any) => {
  backInitParams.push(JSON.parse(JSON.stringify(initParams)));
  initParams.id = row.id;
};

const back = () => {
  const index = backInitParams.length - 1;
  initParams.id = backInitParams[index].id;
  backInitParams.pop();
};

// --------地区处理
const operaProvince = (level: "province" | "city" | "district" | "custom") => {
  if (level === "province") return "省份/行政区";
  if (level === "city") return "城市/区";
  if (level === "district") return "镇/街道";
  if (level === "custom") return "自定义区域";
};

const nextRegion = (level: "province" | "city" | "district" | "custom") => {
  if (level === "province") return "city";
  if (level === "city") return "district";
  if (level === "district") return "custom";
};

const regionDrawerRef = ref<InstanceType<typeof regionDrawer> | null>();
const addRootRegion = () => {
  const row: any = {
    rowData: { name: "", level: "province", pid: 1, sort: 100 },
    api: addRegionApi,
    getTable: regionRef.value?.getTableList
  };
  regionDrawerRef.value?.acceptParams(row);
};
const addRegion = (params: any) => {
  const row: any = {
    rowData: { name: "", level: nextRegion(params.level), pid: params.id, sort: 100 },
    api: addRegionApi,
    getTable: regionRef.value?.getTableList
  };
  regionDrawerRef.value?.acceptParams(row);
};

const editRegion = (params: any) => {
  const row: any = {
    rowData: params,
    api: editRegionApi,
    getTable: regionRef.value?.getTableList
  };
  regionDrawerRef.value?.acceptParams(row);
};

const deleteRegion = async (ids: any) => {
  await useHandleData(deleteApi, { ids }, "删除所选地区");
  regionRef.value?.clearSelection();
  regionRef.value?.getTableList();
};
</script>

<style></style>
